<?php defined('SYSPATH') or die('No direct access allowed.');

class Model_Api_V2_Combination
{
    /**
     * 类型id
     */
    const TYPE_ID = 23;

    /**
     * 允许使用model
     */
    const IS_ABLE_MODEL = array(
        '1' => '线路',
        '2' => '酒店',
        '3' => '租车',
        '5' => '景点',
        '114' => '户外'
    );

    /**
     * 获取属性列表
     * @return array[]
     */
    public static function get_attributes()
    {
        // 自定义属性
        $attr = Model_Api_V2_Combination::get_attribute_by_pid();

        $attr_list  = array();
        $index_attr = array();
        foreach ($attr as $v) {
            $v['name']  = $v['attrname'];
            $v['child'] = Model_Api_V2_Combination::get_attribute_by_pid($v['id']);
            if ($v['child']) {
                foreach ($v['child'] as &$val) {
                    $val['name']  = $val['attrname'];
                    $index_attr[] = $val;
                }
                $attr_list[] = $v;
            }
        }

        return array(
            'attr_list' => $attr_list,
            'index_attr' => $index_attr
        );
    }

    /**
     * 按pid获取属性
     * @param $pid
     * @return array
     */
    public static function get_attribute_by_pid($pid = 0)
    {
        return DB::select('id', 'attrname', 'pid')
            ->from("combination_attr")
            ->where('isopen', '=', 1)
            ->where('pid', '=', $pid)
            ->execute()
            ->as_array();
    }

    /**
     * 获取产品类型名称字符串
     * @param $combination_id
     * @return string
     */
    public static function get_product_type_name($combination_id)
    {
        $types     = DB::select('typeid')
            ->from('combination_product')
            ->where("combination_id", "=", "{$combination_id}")
            ->execute()
            ->as_array();
        $type_name = array();
        if ($types) {
            $is_able_model = Model_Api_V2_Combination::IS_ABLE_MODEL;
            foreach ($types as $v) {
                if (isset($is_able_model[$v['typeid']])) {
                    $type_name[] = $is_able_model[$v['typeid']];
                }
            }
        }
        return implode('+', $type_name);
    }

    /**
     * 获取扩展信息
     * @param $combination_id
     * @return array
     */
    public static function get_extend_info($combination_id)
    {
        $data        = array();
        $extend_info = DB::select()
            ->from('combination_extend_field')
            ->where('productid', '=', $combination_id)
            ->execute()
            ->current();
        if ($extend_info) {
            foreach ($extend_info as $k => $v) {
                if ($k != 'productid' && $k != 'id' && $v) {
                    $chinese_name = DB::select()
                        ->from("combination_content")
                        ->where('columnname', '=', $k)
                        ->execute()
                        ->get('chinesename');
                    $data[]       = array(
                        'name' => $chinese_name,
                        'content' => $v
                    );
                }
            }
        }
        return $data;
    }

    /**
     * @param $id
     * @return int|mixed
     * 获取所有套餐最低价总合
     */
    public static function get_total_min_price($id)
    {
        $product_list = DB::select()
            ->from("combination_product")
            ->where("combination_id", "=", "{$id}")
            ->execute()
            ->as_array();
        $date         = strtotime(date('Ymd', time()));
        $min_price    = 0;
        if ($product_list) {
            foreach ($product_list as $v) {
                $price     = DB::select(DB::expr('min(price) AS price'))
                    ->from('combination_product_price')
                    ->where("combination_product_id", "=", "{$v['id']}")
                    ->and_where("day", ">=", "{$date}")
                    ->and_where('price', '>', 0)
                    ->execute()
                    ->get('price');
                $min_price = bcadd($min_price, $price, 2);
            }
        }

        return Currency_Tool::price($min_price);
    }

    /**
     * @param $id
     * @return array
     * 获取组合套餐
     */
    public static function suit($id)
    {
        $date         = strtotime(date('Ymd', time()));
        $sql          = "SELECT a.id,a.combination_id,a.product_id,a.typeid,a.suit_name,a.suit_describe,a.suit_id FROM sline_combination_product AS a ";
        $sql          .= "LEFT JOIN sline_combination_product_price AS b ON(a.id=b.combination_product_id) ";
        $sql          .= "WHERE a.ishidden<1 AND a.combination_id={$id} AND b.day>={$date} GROUP BY a.id";
        $product_list = DB::query(1, $sql)->execute()->as_array();

        $suit_status = true;
        foreach ($product_list as &$v) {
            if ($v['typeid'] == 114) {
                $v['outdoor'] = self::get_outdoor($v);
            }
            $v['piclist']   = self::get_piclist($v);
            $v['suit_list'] = self::get_suit($v);
            $v['status']    = true;
            if (!$v['suit_list']) {
                $v['status'] = false;
                $suit_status = false;
            }
        }

        return array('product_list' => $product_list, 'suit_status' => $suit_status);
    }

    /**
     * @param $data
     * @return mixed|null
     * 获取户外详细信息
     */
    public static function get_outdoor($data)
    {
        $outdoor                = DB::select('lineday', 'finaldestid', 'startcity', 'gatherflag', 'gather_time')
            ->from('outdoor')
            ->where("id={$data['product_id']}")
            ->execute()
            ->current();
        $outdoor['finaldestid'] = DB::select()
            ->from('destinations')
            ->where("id={$outdoor['finaldestid']}")
            ->execute()
            ->get('kindname');
        $outdoor['startcity']   = DB::select()
            ->from('startplace')
            ->where("id={$outdoor['startcity']}")
            ->execute()
            ->get('cityname');
        return $outdoor;
    }

    /**
     * @param $data
     * @return array
     * 获取组合套餐关联产品的套餐
     */
    public static function get_suit($data)
    {
        $description = $data['typeid'] == 3 ? 'content as description' : 'description';
        $field_name  = $data['typeid'] == 2 ? $description . ',breakfirst,computer,roomstyle,roomarea,roomfloor,roomwindow,people_limit,servicelist,piclist' : $description;
        $table_name  = Model_Combination::get_table_name($data['typeid']);
        $date        = strtotime(date('Ymd', time()));
        $suit_list   = DB::select(DB::expr("id,{$table_name[2]} as suit_name,{$field_name},{$data['typeid']} as typeid"))
            ->from($table_name[0])
            ->where("id in({$data['suit_id']})")
            ->execute()
            ->as_array();
        $suit_arr    = array();
        foreach ($suit_list as $v) {
            if ($v['piclist']) {
                $pic_list = array();
                $piclist  = explode(',', $v['piclist']);
                foreach ($piclist as $val) {
                    $pic  = explode('||', $val);
                    $link = Model_Api_V2_System::uniapp_img($pic[0], 750, 400);
                    array_push($pic_list, $link);
                }
                $v['piclist'] = $pic_list;
            }
            if ($v['servicelist']) {
                $service_list      = DB::select()
                    ->from('hotel_service')
                    ->where("id IN({$v['servicelist']}) and isopen=1")
                    ->execute()
                    ->as_array();
                $v['service_list'] = self::room_service($service_list);
            }

            $price_number = self::testing_product_number($data, $date, $v);
            if ($price_number[1]) {
                $v['price'] = Currency_Tool::price($price_number[0]);
                array_push($suit_arr, $v);
            }
        }
        return $suit_arr;
    }

    /**
     * @param $service_list
     * @return array
     * 组装房型设施
     */
    public static function room_service($service_list)
    {
        $arr = array();
        foreach ($service_list as $v) {
            $arr[$v['pid']][] = $v;
        }
        $list = array();
        $num  = 0;
        foreach ($arr as $k => $v) {
            $list[$num]['top_name'] = DB::select()->from('hotel_service')->where("id={$k}")->execute()->get('attrname');
            $list[$num]['sub_list'] = $v;
            $num++;
        }
        return $list;
    }

    /**
     * @param $data
     * @param $date
     * @param $info
     * @return array
     * 判断库存状态
     */
    private static function testing_product_number($data, $date, $info)
    {
        $combination_product_info = DB::select()->from('combination_product')->where("id={$data['id']}")->execute()->current();
        $table_name               = Model_Combination::get_table_name($combination_product_info['typeid']);
        $price_info               = DB::select()->from("combination_product_price")
            ->where("combination_product_id={$data['id']} and day>={$date} and suitid={$info['id']}")
            ->order_by('day', 'ASC')
            ->execute()
            ->as_array();

        $start_day = reset($price_info);
        $end_day   = end($price_info);
        if ($start_day && $end_day) {
            $filed_name = $combination_product_info['typeid'] == 5 ? 'ticketid' : 'suitid';/*套餐报价表,套餐id字段名称*/

            $product_suit_price = DB::select()->from($table_name[0] . '_price')
                ->where("{$table_name[1]}={$combination_product_info['product_id']} AND {$filed_name}={$info['id']} AND day>={$start_day['day']} AND day<={$end_day['day']}")
                ->execute()->as_array();
            $number_status      = false;
            $start_day['price'] = bcadd($start_day['price'], $start_day['price_difference'], 2);
            if ($product_suit_price) {
                foreach ($product_suit_price as $v) {
                    if ($v['number'] > 0 || $v['number'] == -1) {
                        $number_status = true;
                    }
                }
            }
        } else {
            $start_day['price'] = 0;
            $number_status      = false;
        }

        return array($start_day['price'], $number_status);
    }

    /**
     * @param $data
     * @return array
     * 获取对应产品的图片
     */
    public static function get_piclist($data)
    {
        $table_name = Model_Combination::get_table_name($data['typeid']);

        $piclist = DB::select('piclist')
            ->from($table_name[3])
            ->where("id={$data['product_id']}")
            ->execute()
            ->get('piclist');
        $piclist = Product::pic_list($piclist);
        $p       = array();
        foreach ($piclist as $pic) {
            $pi = Model_Api_V2_System::uniapp_img($pic[0], 750, 400);
            array_push($p, $pi);
        }
        $piclist = $p;

        return $piclist;
    }

    /**
     * @param $combination_product_id
     * @param $suitid
     * @param $typeid
     * @return array
     * 获取日历报价
     */
    public static function calendar_price($combination_product_id, $suitid, $typeid)
    {
        $day            = strtotime(date('Y-m-d', time()));
        $calendar_price = DB::select()->from('combination_product_price')
            ->where("combination_product_id={$combination_product_id} and suitid={$suitid} and day>={$day}")
            ->order_by('day', 'ASC')
            ->execute()
            ->as_array();
        $date_arr       = array();
        $table_name     = Model_Combination::get_table_name($typeid);
        $flie_name      = $typeid == 5 ? "ticketid" : "suitid";
        foreach ($calendar_price as $k => $v) {
            $info       = DB::select()->from($table_name[0] . '_price')->where("day={$v['day']} and {$flie_name}={$suitid}")->execute()->current();
            $product_id = $info[$table_name[1]];
            $number     = '';
            if ($product_id) {
                $number = DB::select()->from('combination_product_calendar_number')
                    ->where("type_id={$typeid} and product_id={$product_id} and suit_id={$suitid} and day={$v['day']}")
                    ->execute()->get('number');
            }
            if ($number === '0') {
                unset($calendar_price[$k]);
                continue;
            } else {
                $number = $number > 0 ? $number : $info['number'];
            }
            if ($number > 0 || $number < 0) {
                $date_arr[$k]['number']         = $number;
                $date_arr[$k]['day']            = $v['day'];
                $date_arr[$k]['departure_time'] = date('Y-m-d', $v['day'] + 86400);/*默认离店时间*/
                $date_arr[$k]['fulldate']       = date('Y-m-d', $v['day']);
                $date_arr[$k]['price']          = Currency_Tool::price(bcadd($v['price'], $v['price_difference'], 2));
            }
        }

        if ($typeid == 2 || $typeid == 3) {
            $date = array();
            foreach ($date_arr as $v) {
                $date[$v['day']] = $v;
            }
            $first           = reset($date);
            $last            = end($date);
            $time_difference = ($last['day'] - $first['day']) / 86400;/*计算相差多少天*/
            /*循环判断缺少那天的报价，并插入缺少部分*/
            $data = array();
            for ($i = 0; $i <= $time_difference; $i++) {
                $day = $first['day'] + $i * 86400;
                if ($date[$day]) {
                    $data[$i] = $date[$day];
                } else {
                    /*判断当前时间前一天是否有报价没有就不添加*/
                    $day2 = $day - 86400;
                    if ($date[$day2]) {
                        $data[$i] = array(
                            'date' => date('m-d', $day),
                            'day' => $day,
                            'daynum' => date('j', $day),
                            'digital' => date('j', $day),
                            'fulldate' => date('Y-m-d', $day),
                            'weekday' => Model_Api_V2_System::get_weekday($day),
                            'status' => 1
                        );
                    }
                }
            }
            if ($typeid == 2) {
                $par = array(
                    'date' => date('m-d', $last['day'] + 86400),
                    'day' => $last['day'] + 86400,
                    'daynum' => date('j', $last['day'] + 86400),
                    'digital' => date('j', $last['day'] + 86400),
                    'fulldate' => date('Y-m-d', $last['day'] + 86400),
                    'weekday' => Model_Api_V2_System::get_weekday($last['day'] + 86400),
                    'status' => 1
                );
                array_push($data, $par);
            }
            $date_arr = array_merge($data, array());
        }

        return $date_arr;
    }

    /**
     * @param $id
     * @param $mid
     * @return array
     * 获取订单信息
     */
    public static function order_detail($id, $mid)
    {
        $query = DB::select('ordersn')->from('member_order')->where('id', '=', $id);
        if (!empty($mid)) {
            $query->and_where('memberid', '=', $mid);
        }
        $info                = $query->execute()->current();
        $info                = Model_Member_Order::order_info($info['ordersn'], null, 1);
        $info['dingnum']     = intval($info['dingnum']);
        $info['singleJifen'] = intval(intval($info['needjifen']) / intval($info['dingnum']));
        $info['litpic']      = Model_Api_V2_System::uniapp_img($info['litpic']);
        $info['add_time']    = date('Y-m-d H:i:s', $info['addtime']);
        $info['remark']      = unserialize($info['remark'])['book'];
        $info['tourers']     = Model_Member_Order_Tourer::get_tourer_by_orderid($info['id']);/*游客信息*/
        $web_url             = DB::select()->from('weblist')->where('id=1')->execute()->get('weburl');
        $info['web_url']     = $web_url;

        //获得合同信息
        if (!empty($info['contract_id'])) {
            $contract                 = Model_Api_V2_Contract::get_order_contract($info['id']);
            $info['contract_content'] = $contract['status'] ? $contract['data'] : false;
        }

        //收益信息
        $income = Model_Member_Order_Compute::get_income_info($info['id']);
        if (St_Functions::is_normal_app_install('mobiledistribution') && method_exists('Model_Fenxiao', 'get_order_fenxiao_info')) {
            $fenxiao_info              = Model_Fenxiao::get_order_fenxiao_info($info);
            $income['platform_income'] = $income['platform_income'] - floatval($fenxiao_info['commission']) - floatval($fenxiao_info['commission1']) - floatval($fenxiao_info['commission2']) - floatval($fenxiao_info['commission3']);
        }
        if (!empty($income)) {
            $info['income'] = $income;
        }
        if (St_Functions::is_normal_app_install('coupon')) {
            $info['iscoupon'] = Model_Coupon::order_view($info['ordersn']);
            $info['cmoney']   = $info['iscoupon']['cmoney'];
        }
        /*子订单信息*/
        $info['current_verified_num'] = 0;
        $info['sub_order']            = array();
        $sub_order                    = DB::select('ordersn')->from("member_order")->where("pid={$id}")->execute()->as_array();
        $info['refund_status']        = true;
        foreach ($sub_order as $v) {
            $sub_order_info = Model_Member_Order::order_info($v['ordersn'], null, 1);
            if ($sub_order_info['status'] == 5) {
                $info['refund_status'] = false;
            }
            $num = DB::select()->from('member_order_verify')->where("orderid={$sub_order_info['id']}")->execute()->current();
            if ($num) {
                $info['current_verified_num'] += 1;
            }
            $sub_order_info['web_url'] = $web_url;
            $sub_order_info['dingnum'] = intval($sub_order_info['dingnum']);
            $sub_order_info['litpic']  = Model_Api_V2_System::uniapp_img($sub_order_info['litpic']);
            $sub_order_info['addtime'] = date('Y-m-d H:i:s', $sub_order_info['addtime']);
            if ($sub_order_info['typeid'] == 114) {
                $sub_order_info['outdoor'] = self::get_outdoor(array('product_id' => $sub_order_info['productautoid']));
            }
            if (St_Functions::is_normal_app_install('system_docs')) {
                $docs = DB::select()->from('member_order_docs')->where("ordersn", '=', $sub_order_info['ordersn'])->execute()->as_array();
                if ($docs) {
                    foreach ($docs as &$do) {
                        $do['ticket_num']  = $do['UUcode'];
                        $do['ticket_guid'] = $do['UUcode'];
                        $do['status']      = 2;
                    }
                    $sub_order_info["stccs_tickets"] = $docs;
                }
            }
            $sub_order_info['combination_product_name'] = DB::select()
                ->from('combination_product')
                ->where("combination_id={$info['productautoid']} and product_id={$sub_order_info['productautoid']} AND FIND_IN_SET({$sub_order_info['suitid']},suit_id) AND typeid={$sub_order_info['typeid']}")
                ->execute()
                ->get('suit_name');
            array_push($info['sub_order'], $sub_order_info);
        }

        return $info;
    }
}